package com.zslc.securitymonitoring.exception;

import cn.hutool.core.util.ObjectUtil;
import com.zslc.securitymonitoring.util.ResultCMS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 *
 * @author yichangao
 * @date 2024/4/3
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(ServiceException.class)
    public ResultCMS handleServiceException(ServiceException e, HttpServletRequest request) {
        log.error(e.getMessage());
        Integer code = e.getCode();
        if (ObjectUtil.isNotNull(code)) {
            return ResultCMS.fail(code, e.getMessage());
        } else {
            return ResultCMS.fail(5000, e.getMessage());
        }
    }

    /**
     * 全局异常：5000-未知的服务器内部错误
     */
    @ExceptionHandler(Exception.class)
    public ResultCMS fullException(Exception e) {
        log.error(e.getMessage(), e);
        e.printStackTrace();
        return ResultCMS.fail_5000();
    }
}